<?php
/**
 * Created by WarCraft3
 * User: WarCraft3
 * Date: 2021/8/17
 * Time: 10:12
 */

namespace app\api\controller;


use app\admin\model\ExamItem;
use app\admin\model\ExamRecord;
use app\common\controller\Api;
use think\Db;
use think\Exception;
use app\common\controller\Redis;

class Exam extends Api
{
    private $_uid;
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected function _initialize()
    {
        parent::_initialize();
        $jwt = $this->request->header('Authorization');
        if ($jwt) {
            $this->check_token($jwt);
            $this->_uid = $this->_token['uid'];
        } else {
            $this->success('缺少token', '', '401');
        }
    }

    /*
     * 提交考试成绩
     * */
    public function submitExam()
    {
        $insert['record'] = htmlspecialchars_decode($this->request->param('record'));//考试记录
        $insert['auser_id'] = $this->_uid;
        $insert['exam_id'] = $this->request->param('exam_id')??0;//考试id
        $insert['usedtime'] = $this->request->param('usedtime')??0;//用时 分
        $insert['pass'] = $this->request->param('pass')??0;//及格分
        $insert['point'] = $this->request->param('point')??0;//得分
        $insert['xuefen'] = $this->request->param('xuefen')??0;// 获取的学分
        $insert['ispass'] = 0;
        if ($insert['point'] >= $insert['pass']){
            $insert['ispass'] = 1;
        }
        $insert['ctime'] = date('Y-m-d H:i:s',time());
        $old = Db::name('exam_record')->where(['auser_id'=>$this->_uid,'exam_id'=>$insert['exam_id']])->find();

        $perid = Db::name('exam')->where('id', $insert['exam_id'] )->value('period_id');
        $insert['period_id'] = $perid;
        $avideo_id=Db::name('exam')->where('id',$insert['exam_id'])->value('avideo_id');
        $exam_third_count=Db::name('exam_third')->where('avideo_id',$avideo_id)->where('auser_id',$this->_uid)->count();
        if($exam_third_count>=3){
            $this->error('已考试通过三次');
        }
        Db::startTrans();
        try{
            $examdata['avideo_id']=Db::name('exam')->where('id',$insert['exam_id'])->value('avideo_id');
            $examdata['auser_id']=$this->_uid;
            $examdata['point']=$insert['point'];
            Db::name('exam_third')->insertGetId($examdata);

            $ret=true;
            if (!$old){
                $ret = Db::name('exam_record')->insertGetId($insert);
            } else {
                if($old['point']<=$insert['point']){
                    $ret = Db::name('exam_record')->where(['auser_id'=>$this->_uid,'exam_id'=>$insert['exam_id']])->update($insert);
                }
            }
            if ( $ret ) {
                $point=Db::name('point')->where('auser_id',$this->_uid)->where('exam_id',$insert['exam_id'])->where('type',1)->find();
                if ($insert['ispass'] == 1&&!$point){
                    //如果考试通过, 增加学分
                    $data['ctime'] = date('Y-m-d H:i:s',time());
                    $data['xuefen'] = $insert['xuefen'];
                    $data['type'] = '1';
                    $data['exam_id'] = $insert['exam_id'];
                    $data['auser_id'] = $this->_uid;
                    Db::name('point')->insert($data);
                    Db::name('auser')->where('id', $this->_uid)->setInc('xue_fen', $insert['xuefen']);
                }
                Db::commit();
                $this->success('存储考试记录成功');
            } else {
                Db::rollback();
                $this->error('失败');
            }
        }catch(Exception $exception){
            Db::rollback();
            $this->error('失败');
        }

    }
    /**
     * 删除考题,针对该用户隐藏该题.
     */
    public function delete_exam(){
        $exam_id= $this->request->param('exam_id'); //视频id
        if(empty($exam_id)){
            $this->error('参数错误');
        }
        $exam_record=Db::name('exam_record')->where('exam_id',$exam_id)->where('auser_id',$this->_uid)->where('ispass',1)->find();
        if(!$exam_record){
            $this->error('该考试不及格');
        }
        $redis = Redis::getInstance()->getRedisConn();
        $isres = $redis->hExists('user_exam_'.$this->_uid, $exam_id);
        $redis->hSet('user_exam_'.$this->_uid, $exam_id, '1');
        if(!$isres){
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }
    /*
     * 获取考试列表
     * */
    public function exams()
    {
        $uid = $this->_uid;
        $period_id = $this->request->param('period_id');
        $whereperiod = '';
        if ($period_id){
            $whereperiod = ['period_id'=>$period_id];
        }

        $avideo_ids=cate_avideo($uid);
        //根据cid 查询未通过中的未测试的考试
        $result = [];
        $demo = new Demo();
        //未通过---不及格的 考试
        $notrecord = Db::name('exam_record')->where(['auser_id'=>$uid,'ispass'=>'0'])->column('exam_id');
        $examnots=is_del_exam($uid);
        $notpass1 = Db::name('exam')
            ->whereIn('id',$notrecord)
            ->whereIn('avideo_id',$avideo_ids)
            ->where($whereperiod)->select()->each(function ($item) use ($demo){
                $item['exam_item'] = $demo->exam_items($item['id']);
                return $item;
            });
        $result['notpass'] = $notpass1??[];

        $already = Db::name('exam_record')->where(['auser_id'=>$uid])->column('exam_id');

        //未测试的考试
        $undo = Db::name('exam')
            ->whereNotIn('id',$already)
            ->whereIn('avideo_id',$avideo_ids)
//            ->where('cate_id',$cid)
            ->where($whereperiod)
            ->select()->each(function ($item) use ($demo){
                $item['exam_item'] = $demo->exam_items($item['id']);
                return $item;
            });
        $result['undo'] = $undo??[];

        //已通过的考试
        $passed = Db::name('exam_record')->where(['auser_id'=>$uid,'ispass'=> '1'])->column('exam_id');
        $pass = Db::name('exam')
            ->whereIn('id',$passed)
            ->whereIn('avideo_id',$avideo_ids)
            ->whereNotIn('id',$examnots)
//            ->where('cate_id',$cid)
            ->where($whereperiod)
            ->select()->each(function ($item) use ($demo){
                $item['exam_item'] = $demo->exam_items($item['id']);
                return $item;
            });
        $result['passed'] = $pass;

        $this->success('成功',$result);
    }

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 搜索考试
     */
    public function search_exams()
    {
        $uid = $this->_uid;
        $period_id = $this->request->param('period_id');
        $key = $this->request->param('keyword');
        $type = $this->request->param('type');
        $whereperiod = '';
        if ($period_id){
            $whereperiod = ['period_id'=>$period_id];
        }
        $avideo_ids=cate_avideo($uid);
        $pass = Db::name('exam_record')->where(['auser_id'=>$uid,'ispass'=>'1'])->column('exam_id');
        $exam_ids=Db::name('exam')->whereIn('avideo_id',$avideo_ids)->column('id');
        if ($type=='wtg'){
            $ids=[];
            for($i=0;$i<count($exam_ids);$i++){
                if(!in_array($exam_ids[$i],$pass)){
                    $ids[]=$exam_ids[$i];
                }
            }
        }else{
            $ids = Db::name('exam_record')->where(['auser_id'=>$uid,'ispass'=>'1'])->column('exam_id');
        }
        //根据cid 查询未通过中的未测试的考试
        $demo = new Demo();
        $examnots=is_del_exam($uid);
        $exams = Db::name('exam')
            ->whereNotIn('id',$examnots)
            ->where('name|intro','like','%'.$key.'%')
            ->where($whereperiod)
            ->whereIn('id',$ids)
            ->whereIn('avideo_id',$avideo_ids)
            ->select()->each(function ($item) use ($demo){
                $item['exam_item'] = $demo->exam_items($item['id']);
                $item['ptype'] = Db::name('exam_record')->where(['auser_id'=>$this->_uid])->where('exam_id',$item['id'])->value('ispass');
                if(!is_numeric($item['ptype'])){
                    $item['ptype']=2;
                }
                return $item;
            });
        foreach ($exams as $k=>$v){
            if($exams[$k]['ptype']=='1'){
                $passed[]=$exams[$k];
            }elseif($exams[$k]['ptype']=='0'){
                $notpass[]=$exams[$k];
            }elseif ($exams[$k]['ptype']=='2'){
                $undo[]=$exams[$k];
            }
        }
        $result['notpass'] = $notpass??[];
        $result['undo'] = $undo??[];
        $result['passed'] =$passed??[];
        $this->success('成功',$result);
    }
    /*
 * 获取考试列表
 * */
    public function geren_exam()
    {

        $exam_id = $this->request->param('exam_id');
        $exam = Db::name('exam')->where('id',$exam_id)->find();
        $demo = new Demo();
        $exam['exam_item']=$demo->exam_items($exam['id']);
        $ptype = Db::name('exam_record')->where(['auser_id'=>$this->_uid])->where('exam_id',$exam['id'])->value('ispass');
        if(empty($ptype)){
            $ptype='0';
        }
        $exam['ptype']=$ptype;
        $rec = Db::name('exam_record')->where(['auser_id' => $this->_uid,'exam_id' => $exam_id])->order('id desc')->find();
        if ($rec) {
            $arr = json_decode($rec['record'], 1);
            $exam['record']=$arr;
            $exam['point']=$rec['point'];
            $exam['usedtime']=$rec['usedtime'];
        }else{
            $exam['record']=[];
            $exam['point']=0;
            $exam['usedtime']=0;
        }
        $avideo_id=Db::name('exam')->where('id',$exam_id)->value('avideo_id');
        $exam_third_count=Db::name('exam_third')->where('avideo_id',$avideo_id)->where('auser_id',$this->_uid)->count();
        if($exam_third_count>=3){
            $exam_third_status=0;
        }else{
            $exam_third_status=1;
        }
        $surplus_count=3-$exam_third_count;
        if($surplus_count==1){
            $surplus_count='一';
        }elseif ($surplus_count==2){
            $surplus_count='二';
        }elseif ($surplus_count==3){
            $surplus_count='三';
        }
        $exam['surplus_count']=$surplus_count;
        $exam['exam_third_status']=$exam_third_status;
        $this->success('成功',$exam);
    }
    /*
     * 获取考试列表
     * */
    public function all_exams()
    {
        $uid = $this->_uid;
        $whereperiod = '';
        $avideo_ids=cate_avideo($uid);
        //根据cid 查询未通过中的未测试的考试
        $result = [];
        $demo = new Demo();
        //未通过---不及格的 考试
        $notrecord = Db::name('exam_record')->where(['auser_id'=>$uid,'ispass'=>'0'])->column('exam_id');
        $examnots=is_del_exam($uid);
        $notpass1 = Db::name('exam')
            ->whereIn('id',$notrecord)
            ->where($whereperiod)
            ->whereIn('avideo_id',$avideo_ids)->select()->each(function ($item) use ($demo){
                $item['exam_item'] = $demo->exam_items($item['id']);
                return $item;
            });
        $result['notpass'] = $notpass1??[];

        $already = Db::name('exam_record')->where(['auser_id'=>$uid])->column('exam_id');

        //未测试的考试
        $undo = Db::name('exam')
            ->whereNotIn('id',$already)
            ->whereIn('avideo_id',$avideo_ids)
            ->where($whereperiod)
            ->select()->each(function ($item) use ($demo){
                $item['exam_item'] = $demo->exam_items($item['id']);
                return $item;
            });
        $result['undo'] = $undo??[];

        //已通过的考试
        $passed = Db::name('exam_record')->where(['auser_id'=>$uid,'ispass'=> '1'])->column('exam_id');
        $pass = Db::name('exam')
            ->whereIn('id',$passed)
            ->whereNotIn('id',$examnots)
            ->whereIn('avideo_id',$avideo_ids)
            ->where($whereperiod)
            ->select()->each(function ($item) use ($demo){
                $item['exam_item'] = $demo->exam_items($item['id']);
                return $item;
            });
        $result['passed'] = $pass;

        $this->success('成功',$result);
    }
    /*
     * 获取某个考试的答题记录
     * */
    public function answers()
    {
//        $exam_id = $this->request->param('exam_id')??0;//考试id
//        $uid = $this->_uid;
//        $remodel = new ExamRecord();
//        $rec = $remodel::where(['auser_id' => $uid,'exam_id' => $exam_id])->order('id desc')->find();
//        if ($rec){
//            $arr = json_decode($rec->record,1);
//            $exitem = new ExamItem();
//            foreach ($arr as  $k=>$v){
//                $arr[$k]['info'] = $exitem::get($v['id']);
//            }
//            $rec->record = $arr;
//            $rec->paiming  = ords($this->_uid,$exam_id);
//            $avideo_id=Db::name('exam')->where('id',$exam_id)->value('avideo_id');
//            $exam_third_count=Db::name('exam_third')->where('avideo_id',$avideo_id)->where('auser_id',$this->_uid)->count();
//            if($exam_third_count>=3){
//                $exam_third_status=0;
//            }else{
//                $exam_third_status=1;
//            }
//            $rec->intro=Db::name('exam')->where('id',$exam_id)->value('intro');
//            $rec->exam_third_status=$exam_third_status;
//            //排名
////            $data = Db::name('exam_record')
////                ->where('exam_id',$exam_id)
////                ->order('point desc')
////                ->select();
////            $rec->paiming = 1;
////            foreach ($data as $k=>$v){
////                if ($v['point'] <= $rec->point){
////                    if($k == 0){
////                        $rec->paiming = 1;
////                    }else{
////                        $rec->paiming = $k;
////                    }
////                }
////            }
//
//            $this->success('成功',$rec);
//        }
        $exam_id = $this->request->param('exam_id');
        $exam = Db::name('exam')->where('id',$exam_id)->find();
        $demo = new Demo();
        $exam['exam_item']=$demo->exam_items($exam['id']);
        $ptype = Db::name('exam_record')->where(['auser_id'=>$this->_uid])->where('exam_id',$exam['id'])->value('ispass');

        $rec = Db::name('exam_record')->where(['auser_id' => $this->_uid,'exam_id' => $exam_id])->order('id desc')->find();
        if ($rec) {
            $arr = json_decode($rec['record'], 1);
            $exam['record']=$arr;
            $avideo_id=Db::name('exam')->where('id',$exam_id)->value('avideo_id');
            $exam_third_count=Db::name('exam_third')->where('avideo_id',$avideo_id)->where('auser_id',$this->_uid)->count();
            if($exam_third_count>=3){
                $exam_third_status=0;
            }else{
                $exam_third_status=1;
            }
            $exam['exam_third_status']=$exam_third_status;
            $exam['point']=$rec['point'];
            if(empty($ptype)){
                $ptype='0';
            }elseif($exam['point']==$exam['total_point']){
                $ptype='2';
            }
            $exam['ptype']=$ptype;
            $exam['usedtime']=$rec['usedtime'];
            $this->success('成功',$exam);
        }else{
            $this->error('查无此考试');
        }
    }
    /*
     * 获取某个考试的答题记录
     * */
    public function exam_intro()
    {
        $exam_id = $this->request->param('exam_id')??0;//考试id
        $intro=Db::name('exam')->where('id',$exam_id)->value('intro');
        if(!$intro){
            $intro='';
        }
        $this->success('考试说明',$intro);
    }


}